//
//  WHYHomeViewController.swift
//  WHYWeibo-1.0
//
//  Created by 王洪运 on 15/11/22.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit
import SVProgressHUD

let WHYStatusCellNormalID = "WHYStatusCellNormalID"
let WHYStatusCellRetweetedID = "WHYStatusCellRetweetedID"

class WHYHomeViewController: WHYVisitorTableViewController {
    
    private var listViewModel = WHYStatusListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        if !WHYUserAccountViewModel.sharedUserAccount.userLogon {
            visitorView?.setupInfo(imageName: nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        
        prepareTableView()
        loadData()
        
        NSNotificationCenter.defaultCenter().addObserverForName(WHYWBSendStatusNotification,
            object: nil,
            queue: nil) { (_) -> Void in
                self.loadData()
        }
        
        NSNotificationCenter.defaultCenter().addObserverForName(WHYWBStatusSelectedPhotoNotification,
            object: nil,
            queue: nil) { [weak self] (notification) -> Void in
//                QL2(notification.object)
//                QL2(notification.userInfo)
                
                guard let urls = notification.userInfo![WHYWBStatusSelectedPhotoURLKey] as? [NSURL] else {
                    return
                }
                
                guard let selectedIndexPath = notification.userInfo![WHYWBStatusSelectedPhotoIndexPathKey] as? NSIndexPath else {
                    return
                }
                
//                判断cell是否遵守了WHYPhotoBrowserPresentDelegate协议
                guard let cell = notification.object as? WHYPhotoBrowserPresentDelegate else {
                    return
                }
                
                let browserVc = WHYPhotoBrowserViewController(urls: urls, selectedIndexPath: selectedIndexPath)
                
                browserVc.modalPresentationStyle = UIModalPresentationStyle.Custom
                
                browserVc.transitioningDelegate = self?.photoBrowserAnimator
                
//                控制器告诉photoBrowserAnimator的presentDelegate和dismissDelegate是谁，并且告诉photoBrowserAnimator具体是哪个图片要进行展示
                self?.photoBrowserAnimator.setupDelegateParameters(cell, dismissDelegate: browserVc, indexPath: selectedIndexPath)
                
                self?.presentViewController(browserVc, animated: true, completion: nil)
        }
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func prepareTableView () {
        tableView.registerClass(WHYStatusNormalCell.self, forCellReuseIdentifier: WHYStatusCellNormalID)
        tableView.registerClass(WHYStatusRetweetedCell.self, forCellReuseIdentifier: WHYStatusCellRetweetedID)
        
        tableView.separatorStyle = .None
        
        tableView.estimatedRowHeight = 400//预估的最大高度
//        tableView.rowHeight = UITableViewAutomaticDimension//自动计算高度，但需要设置底边的约束。如果没有自动计算，那么不能设置底边的约束，否则约束会计算错误
        
//        下拉刷新控件
        refreshControl = WHYRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
        
//        上拉加载数据
        tableView.tableFooterView = pullupView
        
    }

    @objc private func loadData() {
        
        refreshControl?.beginRefreshing()
        
        listViewModel.loadStatus(isPullup: pullupView.isAnimating()) { (isSuccessed) -> () in
            
            self.refreshControl?.endRefreshing()
            self.pullupView.stopAnimating()
            
            if !isSuccessed {
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
                return
            }
            
            self.showPullDownTip()
            
//            QL2(self.listViewModel.statusList.first)
            self.tableView.reloadData()
        }
        
    }
    
// MARK: - 懒加载子控件
    private lazy var photoBrowserAnimator = WHYPhotoBrowserAnimator()
    
    private lazy var pullupView: UIActivityIndicatorView = {
        
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
        indicator.color = UIColor.lightGrayColor()
        
        return indicator
    }()
    
    private lazy var pullDownTipLable: UILabel = {
        
        let lable = UILabel(title: "", titleColor: UIColor.whiteColor(), fontSize: 18)
        lable.backgroundColor = UIColor.cyanColor()
        self.navigationController?.navigationBar.insertSubview(lable, atIndex: 0)
        
        return lable
    }()
    
    private func showPullDownTip () {
        
        guard let count = listViewModel.pullDownCount else {
            return
        }
        
        let message = count > 0 ? "刷新了\(count)条微博" : "没有刷新微博"
        
        let h: CGFloat  = 44
        let rect = CGRect(x: 0, y: -2 * h, width: view.bounds.width, height: h)
        
        pullDownTipLable.frame = CGRectOffset(rect, 0, h)
        pullDownTipLable.text = message
        
        UIView.animateWithDuration(0.8, animations: { () -> Void in
            self.pullDownTipLable.frame = CGRectOffset(rect, 0, 3 * h)
            }) { (_) -> Void in
                UIView.animateWithDuration(1.0, animations: { () -> Void in
                    self.pullDownTipLable.frame = rect
                })
        }
        
    }
    
    
}

// MARK: - 数据源和代理方法
extension WHYHomeViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let vm = listViewModel.statusList[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(vm.cellID, forIndexPath: indexPath) as! WHYStatusCell
        
        if indexPath.row == listViewModel.statusList.count - 1 && !pullupView.isAnimating() {
            pullupView.startAnimating()
            loadData()
        }
        
        cell.viewModel = vm
        cell.cellDelegate = self
        
        return cell
        
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return listViewModel.statusList[indexPath.row].rowHeight
    }
    
}

extension WHYHomeViewController: WHYStatusCellDelegate {
    
    func statusCellClickURL(url: NSURL) {
        
        let webVc = WHYHomeWebViewController(url: url)
        webVc.hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(webVc, animated: true) 
    }
    
}
